// pages/home/index/index.js
import * as echarts from '../../../component/ec-canvas/echarts';
const call = require('../../../utils/request.js')
const util = require('../../../utils/util.js')
let chart = null; //折线图
let barComponent = null;
let startPoint; //客服咨询弹窗位置
let app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    buttonTop: 0,
    buttonLeft: 0,
    windowHeight: '',
    windowWidth:'',
    isNewPerson1:false, //显示第一个提示窗口
    isNewPerson2:false, //显示第二个提示窗口
    isNewPerson3:false, //显示第三个提示窗口
    isNewPerson4:false, //显示第四个提示窗口
    hasHis: 0, 
    xtText:{
      1:{
        name:"血糖正常",
        color:"green",
        tip:"您当前血糖正常,请您继续保持"
      },
      2:{
        name:"血糖偏低",
        color:"blue",
        tip:"您当前血糖偏低哦,请您加强管控"
      },
      3:{
        name:"血糖偏高",
        color:"red",
        tip:"您当前血糖偏高哦,请您加强管控"
      },
    },
    glucose: {}, //最新血糖信息
    ec: {
      lazyLoad: true
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // barComponent = this.selectComponent('#mychart-dom-bar');

    // app.globalData.isBind = 1
    // app.globalData.isNewPerson = 0

    //获取屏幕高度,方便移动客服咨询窗口定位
    wx.getSystemInfo({
      success: res=> {
        // 高度,宽度 单位为px
        this.setData({
          windowHeight:  res.windowHeight,
          windowWidth:  res.windowWidth,
          buttonTop: res.windowHeight - 87,
          buttonLeft: res.windowWidth - 77,
        })
      }
    })
    
    // console.log(app.globalData.isBind,app.globalData.isNewPerson)
    //如果是手机绑定的用户且 是 新绑定的，弹出操作引导并且将新用户的状态值取消
    if(app.globalData.isBind == 1 && app.globalData.isNewPerson == 0){
      //隐藏tabbar，避免遮挡
      wx.hideTabBar();
      //设置为新客户，显示弹窗
      this.setData({isNewPerson1:true})
      app.globalData.isNewPerson == 1;
    }else{
      //先加载echart图再调用数据，避免无渲染
      // initChart().then(()=>{
      //   this.getDayStatistics();
      // });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getInfo();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 页面跳转
   */
  toUrl(e){
    //判断是否登录
    if(app.globalData.isBind == 0){
      wx.reLaunch({
        url:'../../login/index/index'
      });
      return;
    }
    const url = e.currentTarget.dataset.url;
    console.log(url)
    wx.navigateTo({
      url: `../../../home/${url}`,
    })
  },

  /**
   * 客服咨询
   */
  callPhone(){
    wx.makePhoneCall({
      phoneNumber: '18073907266',
      success(){console.log(1)},
      fail(){console.log(2)},
      complete(){console.log(3)}
    })
  },

  /**
   * 获取基本数据信息（血糖值）
   */
  getInfo(){
    // wx.showLoading({
    //   title: '加载中',
    //   mask: true
    // })
    call.post('/api/index/index_data').then(res=>{
      console.log("获取基本数据信息（血糖值）",res)
      this.setData({
        info: res.data.data
      })
      // wx.hideLoading();
    })
  },

  /** 
   * 统计 -- 日统计
   */
  getDayStatistics(){
    // let timer = null;
    // if(!chart){
    //   timer = setTimeout(()=>{this.getDayStatistics();},200);
    //   return;
    // }
    // clearTimeout(timer);
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    call.post('/api/index/day_log',{
      // time: this.data.time
    }).then(res=>{
      wx.hideLoading();
      console.log("日统计",res)
      const DayStatistics = res.data.data;
      //保存最新血糖数据
      this.setData({
        hasHis: (DayStatistics.glucose.length),
        glucose: (DayStatistics.glucose[DayStatistics.glucose.length-1])
      })
      //刷新当前折线图  arr胰岛素 arr1正常 arr2低血糖 arr3高血糖
      if(DayStatistics.glucose.length > 0){
        let arr = [],arr1 = [];
        for(let i of DayStatistics.glucose){
          arr.push([i.test_at,i.glu])
        }
        let time = arr[0][0].split(' ')[0];
        let time1 = util.formatTime(new Date(new Date(time).getTime()+24*60*60*1000),"date");
        arr1 = [[time+" 00:00:00",0],[time1+" 00:00:00",0]]
        
        chart.setOption({
          series: [{
            data: arr,
          },{
            data:arr1,
          }]
        })
        
      }
    })
  },

  /**
   * 新用户弹窗指引 下一步
   */
  nextLoad(e){
    const key = e.currentTarget.dataset.page;
    let data = {
      [`isNewPerson${key}`]:false,
    }
    
    if(key!="4"){
      data = Object.assign(data,{[`isNewPerson${parseInt(key)+1}`]:true})
    }else{
      wx.showTabBar();
      //加载echart图
      // initChart();
    }
    this.setData(data)
  },
  
  /**
   * 客服咨询弹窗的移动 
   */
  buttonStart: function (e) {
    startPoint = e.touches[0]
  },
  buttonMove: function (e) {
    var endPoint = e.touches[e.touches.length - 1]
    var translateX = endPoint.clientX - startPoint.clientX
    var translateY = endPoint.clientY - startPoint.clientY
    startPoint = endPoint
    var buttonTop = this.data.buttonTop + translateY
    var buttonLeft = this.data.buttonLeft + translateX
    //判断是移动否超出屏幕
    if (buttonLeft+50 >= this.data.windowWidth){
      buttonLeft = this.data.windowWidth-50;
    }
    if (buttonLeft<=0){
      buttonLeft=0;
    }
    if (buttonTop<=0){
      buttonTop=0
    }
    if (buttonTop + 50 >= this.data.windowHeight){
      buttonTop = this.data.windowHeight-50;
    }
    this.setData({
      buttonTop: buttonTop,
      buttonLeft: buttonLeft
    })
  },
  buttonEnd: function (e) {

  }

})


/**
 * 获取dpr
 */
function getPixelRatio(){
  let pixelRatio = 0
  wx.getSystemInfo({
    success: function (res) {
      pixelRatio = res.pixelRatio
    },
    fail: function () {
      pixelRatio = 0
    }
  })
  return pixelRatio
}

/**
 * 日统计 -- 曲线图
 */

function initChart(canvas, width, height, dpr) {
  return new Promise((resolve,reject)=>{
    dpr=getPixelRatio();
    barComponent.init((canvas,width,height)=>{
      chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      var axisCommonX = {
        type: 'time',
        boundaryGap:false,
        splitLine:{
          show:false
        },
        axisLabel: {
          textStyle: {
            color: '#333333'
          },
          formatter: function(value, index){
            var t_date = new Date(value);
            let hour = t_date.getHours()<10?'0'+t_date.getHours():t_date.getHours();
            let min = t_date.getMinutes()<10?t_date.getMinutes()+'0':t_date.getMinutes();
            return [hour, min].join(':');
          },
        },
        // 超出的部分
        axisTick: {
          show:false
        },
        // 最外层坐标轴
        axisLine: {
          lineStyle: {
            color: '#C8C8C8',
            type: 'dotted'
          }
        },
        // 网格线
        splitLine: {
          show:false
        },
      },
      axisCommonY = {
        type:'value',
        max:40,
        min:0,
        // 坐标轴字体
        axisLabel: {
          textStyle: {
            color: '#C8C8C8'
          }
        },
        // 超出的部分
        axisTick: {
          show:false
        },
        // 最外层坐标轴
        axisLine: {
          show:false
        },
        // 网格线
        splitLine: {
          lineStyle: {
            color: '#C8C8C8',
            type: 'dotted'
          }
        },
      };
      var option = {
        grid:{
          top: 20,
          bottom:30,
          right: 20,
          left: 30
        },
        color: ["#00726D"],
        backgroundColor: '#FFF',
        xAxis: axisCommonX,
        yAxis: axisCommonY,
        // 数据图形显示
        series: [{
          type: 'line',
          symbol: 'circle',
          symbolSize:10,
          hoverAnimation: false,
          name: 'aaaa',
          data: [],
          // markPoint: {
          //   label: {
          //     normal: {
          //       show: true,
          //       backgroundColor: '#00726D',
          //       position: 'top',
          //       color: '#FFF',
          //       borderColor: '#00726D',
          //       borderWidth: 1,
          //       borderRadius:5,
          //       padding: 2,
          //       formatter: `{c}\nmmol/L`
          //     }
          //   },
          //   symbol: 'circle',
          //   symbolSize: 7,
          //   data: [
          //     { type: 'max', name: 'Max' }
          //   ]
          // },
          lineStyle: { normal: { color: '#00726D', width: 1 } },
        },{
          name:'.anchor',
          type:'line', 
          showSymbol:false, 
          data:[[`2020-08-23 00:00:00`,0],[`2020-08-24 00:00:00`,0]],
          itemStyle:{normal:{opacity:0}},
          lineStyle:{normal:{opacity:0}}
        }],
        tooltip: {  
          show: true,
          trigger: 'axis',
          backgroundColor: '#00726D',
          position: 'top',
          color: '#FFF',
          borderColor: '#00726D',
          borderWidth: 1,
          borderRadius:5,
          padding: 2,
          textAlign:'center',
          // /*返回需要的信息*/  
          formatter: function(param) {  
              var value = param[0].value; 
              let time = value[0].split(' ')[1];
              time = time.substring(0,time.length - 3);
              return `${time}\n${value[1]}mmol/L`;  
          }  
        },
      
        animationDelay: function (idx) {
          return idx * 50;
        },
        animationEasing: 'elasticOut'
      };
      canvas.setChart(chart);
      chart.setOption(option);
      resolve();
      return chart;
    })
  })
}